package com.zhuang.rabbitmq.all;


import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @Classname Producer
 * @Description 消费者
 * @Date 2021/4/15 15:38
 * @Created by dell
 */

public class Producer {
    public static void main(String[] args) {
        // 创建连接工程
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("192.168.152.130");
        connectionFactory.setPort(5672);
        connectionFactory.setUsername("admin");
        connectionFactory.setPassword("admin");
        connectionFactory.setVirtualHost("/");
        //创建Connection
        Connection connection = null;
        Channel channel = null;
        try {
            connection = connectionFactory.newConnection("生产者");
            //通过连接获得通道Channel
            channel = connection.createChannel();

            //声明交换机名称
            String exchangeName="all_message_exchange";
            //交换机类型
            String exchangeType="direct";
            //定义一个交换机
            channel.exchangeDeclare(exchangeName,exchangeType,true);

            //声明队列
            channel.queueDeclare("queue5",true,false,false,null);
            channel.queueDeclare("queue6",true,false,false,null);
            channel.queueDeclare("queue7",true,false,false,null);

            //绑定队列和交换机的关系
            channel.queueBind("queue5",exchangeName,"order");
            channel.queueBind("queue6",exchangeName,"order");
            channel.queueBind("queue7",exchangeName,"order");
          //  String queueName = "queue1";
            /*
            队列名称
            是否要持久化
            排他性
            是否自动删除
            携带附属参数
             */
            String message = "hello kang xiao zhuang";
            //发送消息给队列
            channel.basicPublish(exchangeName,"order", null, message.getBytes());

            System.out.println("消息发送成功");
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        } finally {
            if (channel != null && channel.isOpen()) {
                try {
                    connection.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
